-- 清理3天前的日志数据
local now = os.time()
local three_days_ago = now - (3 * 24 * 60 * 60)

local log_file = io.open("/usr/local/openresty/nginx/logs/stats.log", "r")
if not log_file then
    return
end

local lines = {}
for line in log_file:lines() do
    local time_str = line:match("([^|]+)")
    if time_str then
        local year, month, day, hour, min = time_str:match("(%d+)-(%d+)-(%d+) (%d+):(%d+)")
        if year then
            local log_time = os.time({
                year = tonumber(year),
                month = tonumber(month),
                day = tonumber(day),
                hour = tonumber(hour),
                min = tonumber(min),
                sec = 0
            })
            -- 保留3天内的数据
            if log_time >= three_days_ago then
                table.insert(lines, line)
            end
        end
    end
end
log_file:close()

-- 重写日志文件
local log_file_write = io.open("/usr/local/openresty/nginx/logs/stats.log", "w")
if log_file_write then
    for _, line in ipairs(lines) do
        log_file_write:write(line .. "\n")
    end
    log_file_close()
end
